/// 加载错误
#[derive(Debug)]
pub enum LoadError
{
    File(String),
    Deserialize(String),
}

/// 保存错误
#[derive(Debug)]
pub enum SaveError
{
    File(String),
    Serialize(String),
}

/// 加载配置文件
pub fn load<T>(path: &str) -> Result<T, LoadError>
where
    T: for<'a> serde::de::Deserialize<'a>,
{
    match std::fs::read(path)
    {
        Ok(v) =>
        {
            match serde_json::from_slice::<T>(v.as_slice())
            {
                Ok(config) => Ok(config),
                Err(e) => Err(LoadError::Deserialize(format!("{:?}", e))),
            }
        }
        Err(e) => Err(LoadError::File(format!("{:?}", e))),
    }
}

/// 保存配置文件
pub fn save<T>(value: &T, path: &str) -> Result<(), SaveError>
where
    T: ?Sized + serde::Serialize,
{
    match serde_json::to_string_pretty(value)
    {
        Ok(config) =>
        {
            match std::fs::write(path, config)
            {
                Ok(_) => Ok(()),
                Err(e) => Err(SaveError::File(format!("{:?}", e))),
            }
        }
        Err(e) => Err(SaveError::Serialize(format!("{:?}", e))),
    }
}
